<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20210822
 * Time: 11:05 
 * 盈利率管理
 */
namespace app\api\controller;

use  Mscore\Core\Controller;
use  app\api\model\Zerotrade as ZerotradeModel;
use  app\api\model\Common as CommonModel;
use  app\api\model\Login as LoginModel;
use  Mscore\Core\Util\Util;
use  Mscore\Core\Lang;

class ZerotradeController extends Controller{

    private $model;
    private $login;
    private $error;
    private $success;
    /**
     * 初始化自动连接方法
     * @param array $__construct 
     * @param array $where 
    */
    public function __construct()  
    {    
        $this->model = new ZerotradeModel;
        $this->login = (new LoginModel)->isAuth();
        $this->header =get_all_headers();
        $this->header['language']=isset($this->header['language'])&&!empty($this->header['language'])?$this->header['language']:config('langs.default');
        Lang::init($this->header['language']);
        $this->success=Lang::get('Success');
        $this->error=Lang::get('Error');
    }
    /**
     * 产品类别列表
     * @param array $catelist 
     * @param array $where 
     */ 
    public function catelist(){
        $pro=[];
        switch (true) {
            case !empty(post('id')):
                $where = 'a.id='.post('id');
                $pro = $this->model->catelist($where);
                $this->success['data']=$pro['data'];
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = 'a.dels<1';
                $pro = $this->model->catelist($where,$page,$limit);
                $this->success['data']=$pro['data'];
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
        } 
    }
    /**
     * 产品列表
     * @param array $zerotrade 
     * @param array $where 
     */ 
    public function zerotrade(){
        $pro=[];
        switch (true) {
            case !empty(post('id')):
                $where = 'a.id='.post('id');
                $pro = $this->model->zerorate($where);
                if(!empty($pro['data'][0]['titles'])){
                    $pro['data'][0]['title']=isset(json_decode($pro['data'][0]['titles'],true)[$this->header['language']])?json_decode($pro['data'][0]['titles'],true)[$this->header['language']]:$pro['data'][0]['title'];
                    $pro['data'][0]['price']=0;
                    unset($pro['data'][0]['titles']);
                }
                $this->success['data']=$pro['data'];
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = 'a.dels<1 and a.status<3';
                if(!empty(post('cid'))){
                    $where .= ' and a.cid='.post('cid');
                }
                if(!empty(post('keyworld'))){
                    $where .= ' and ( a.title like "%'.post('keyworld').'%" or a.procode like "%'.post('keyworld').'%" ) ';
                }
                $pro = $this->model->zerorate($where,$page,$limit);
                $procode = '';
                foreach ($pro['data'] as $key => $value) {
                    if(!empty($value['titles'])){
                        $pro['data'][$key]['title']=isset(json_decode($value['titles'],true)[$this->header['language']])?json_decode($value['titles'],true)[$this->header['language']]:$value['title'];  
                    }
                    $pro['data'][$key]['price']=0;
                    $procode .= $value['procode'].',';
                    unset($pro['data'][$key]['titles']);
                }
                $this->success['data']=$pro['data'];
                $this->success['procode']=$procode;
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
        } 
    }
    /**
     * 产品详情
     * @param array $zerotradeinfo 
     * @param array $where 
     */ 
    public function zerotradeinfo(){
        $id=post('id');
        switch (true) {
            case $id>0:
                $where = ' id='.$id;
                $pro = $this->model->zerorateinfo($where);
                if(!empty($pro['titles'])){
                    $pro['title']=isset(json_decode($pro['titles'],true)[$this->header['language']])?json_decode($pro['titles'],true)[$this->header['language']]:$pro['title'];
                    unset( $pro['titles']);
                }
                if(isset($pro)&&!empty($pro)){
                    $fk=$this->model->getorderinfo(' aid='.$this->login['aid'].' and proid='.$id.' and status<2','id');     
                }
                $pro['orderid']=isset($fk['id'])&&!empty($fk['id'])?$fk['id']:1; //2有订单，1无订单
                $this->success['data']=$pro;
                $this->success['count']=1;
                return $this->echojson($this->success);
                break;
            default:
                return $this->echojson($this->error);
                break;
        }
    }
    /**
     * 获取k线图
     */
    public function getKdata(){
        $procode = post('procode',false);
        $page = post('page',1);
        $size = post('page_size',100);
        $time = post('time','1H'); //1M,5M,10M,15M,30M,1H,2H,4H,D,W,M
        if(!$procode){
            return $this->echojson($this->error);
        }
        $data = $this->model->getKdata($procode.'-'.$time.'-'.$page.'-'.$size);
        if(empty($data)){
            $data = $this->model->getApi("procode={$procode}&time={$time}&page={$page}&size={$size}&withlast=0");
            $data = json_decode($data,true);
            if(!isset($data['code']) || $data['code']!=200){
                $code = isset($data['code'])?$data['code']:103;
                $msg = isset($data['msg'])?$data['msg']:'数据请求，接口无反应，请检查网络或其它错误';
                return $this->echojson(['code'=>$code,'msg'=>$msg]);
            }
            if(isset($data['data'])&&!empty($data['data'])){
                $settime=60*60;
                switch ($time) {
                    case '1M':
                        $settime=60;
                        break;
                    case '5M':
                        $settime=60*5;
                        break;
                    case '30M':
                        $settime=60*30;
                        break;
                    case '1H':
                        $settime=60*60;
                        break;
                    case 'D':
                        $settime=60*60*24;
                        break;
                    default:
                        $settime=60*60;
                        break;
                }
                $this->model->setKdata($procode.'-'.$time.'-'.$page.'-'.$size,$data['data'],$settime);
            }
            $data = $data['data'];
        }
        $this->success['data']=$data;
        return $this->echojson($this->success);
    }
    /**
     * 订单list
     * @param array $orderlist 
     * @param array $where 
     */ 
    public function orderlist(){
        switch (true) {
            case !empty(post('id')):
                $where = 'id='.post('id');
                $datalist = $this->model->list($where);
                if(!empty($datalist['data'][0]['titles'])){
                    $datalist['data'][0]['proname']=isset(json_decode($datalist['data'][0]['titles'],true)[$this->header['language']])?json_decode($datalist['data'][0]['titles'],true)[$this->header['language']]:$datalist['data'][0]['proname'];
                    unset($datalist['data'][0]['titles']); 
                }
                $this->success['data']=$datalist['data'];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' dels<1 and aid = '.$this->login['aid'].' and status>1';
                if(post('time')){
                    $time=post('time');
                    switch ($time){
                        case 1:
                            $where .= '';
                            break;
                        case 2:
                            $where .= " and (createtime BETWEEN CONCAT(CURDATE(),' 00:00:00') AND CONCAT(CURDATE(),' 23:59:59')) ";
                            break;
                        case 3:
                            $where .= ' and (TO_DAYS(NOW()) - TO_DAYS(createtime) = 1)';
                            break;
                        case 4:
                            $where .= ' and (WEEK(createtime) = WEEK(CURDATE()))';
                            break;
                        case 5:
                            $where .= " and DATE_FORMAT(createtime,'%Y-%m')= DATE_FORMAT(CURDATE(),'%Y-%m')";
                            break;
                        case 6:
                            $where .= " and (PERIOD_DIFF(DATE_FORMAT(NOW(),'%Y%m'),DATE_FORMAT(createtime,'%Y%m')) = 1)";
                            break;
                        default:
                            return $this->echojson($this->error);
                            break;
                    }
                    
                }
                $datalist = $this->model->list($where,$page,$limit);
                foreach ($datalist['data'] as $key => $value) {
                    if(!empty($value['titles'])){
                        $datalist['data'][$key]['proname']=isset(json_decode($value['titles'],true)[$this->header['language']])?json_decode($value['titles'],true)[$this->header['language']]:$value['proname']; 
                        unset($datalist['data'][$key]['titles']);
                    }
                }
                $this->success['data']=!empty($datalist['data'])?$datalist['data']:[];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
        } 
    }
    /**
     * 订单list
     * @param array $orderlistrun 
     * @param array $where 
     */ 
    public function orderlistrun(){
        switch (true) {
            case !empty(post('id')):
                $where = 'id='.post('id');
                $datalist = $this->model->list($where);
                if(!empty($datalist['data'][0]['titles'])){
                    $datalist['data'][0]['proname']=isset(json_decode($datalist['data'][0]['titles'],true)[$this->header['language']])?json_decode($datalist['data'][0]['titles'],true)[$this->header['language']]:$datalist['data'][0]['proname']; 
                    unset($datalist['data'][0]['titles']); 
                }
                $this->success['data']=$datalist['data'];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' dels<1 and aid = '.$this->login['aid'].' and status<2 ';
                if(post('proname')){
                    $where .= ' and proname like "%'.post('proname').'%"';
                }
                $datalist = $this->model->list($where,$page,$limit);
                foreach ($datalist['data'] as $key => $value) {
                    if(!empty($value['titles'])){
                        $datalist['data'][$key]['proname']=isset(json_decode($value['titles'],true)[$this->header['language']])?json_decode($value['titles'],true)[$this->header['language']]:$value['proname']; 
                        unset($datalist['data'][$key]['titles']);
                    }
                }
                $this->success['data']=!empty($datalist['data'])?$datalist['data']:[];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
        } 
    }
    /**
     * 获取参数
     * @param array $getconfshow 
     * @param array $where 
     */ 
    public function getconfshow(){
        $control=(new CommonModel())->getBaseinfo('keyname="zerocontrol"','content');
        $control=!empty($control)?$control['content']:config('zerocontrol');
        $this->success['data']=$control;
        return $this->echojson($this->success); 
    }
    /**
     * 订单orderadd
     * @param array $orderadd 
     * @param array $where 
     */ 
    public function orderadd(){
        $params = post();
        //判斷參數是否存在
        if(empty($params['proid'])) return $this->echoJson(Lang::get('Proempty'));
        if(empty($params['order_type'])) return $this->echoJson(Lang::get('Updown'));

        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        $user=(new CommonModel())->getAccount('aid='.$this->login['aid'],['aid','amount','giftamount','pid','paypwd']);

        $control=(new CommonModel())->getBaseinfo('keyname="zerocontrol"','content');
        $control=!empty($control)?$control['content']:config('zerocontrol');
        //判斷支付密碼及驗證
        if($control['addorder']==1){
            if(empty($params['pay_password'])) return $this->echoJson(Lang::get('Paypwdempty'));
            if(empty($user['paypwd'])) return $this->echoJson(Lang::get('Paypwdset'));
            if (!Util::passwordVerify($params['pay_password'], $user['paypwd'])) return $this->echojson(Lang::get('Paypwderror'));
        }
        //獲取運營參數
        $pro = $this->model->zerorateinfo('id='.$params['proid'],['id','title','titles','procode','price','bond','orders','fee','minnum','maxnum']);
        if($pro['orders']==1){
            $count=$this->model->getorderinfo('proid='.$params['proid'].' and status<2 and aid='.$this->login['aid'],'count(id) as id');
            if(isset($count['id'])&&!empty($count['id'])){
                return $this->echoJson(Lang::get('Ordercz'));
            }
        }
        if(empty($pro)) return $this->echoJson(Lang::get('Nodata'));
        if(!empty($pro['minnum'])&&$pro['minnum']>$params['puffs']) return $this->echoJson(Lang::get('Ordermin'));
        if(!empty($pro['maxnum'])&&$pro['maxnum']<$params['puffs']) return $this->echoJson(Lang::get('Ordermax'));
        //判断其他参数
        if($params['money_type']==1){
           if($user['amount']<floatval($params['puffs']*$pro['bond'])) return $this->echoJson(Lang::get('Amountfew'));  //用戶金額
        }elseif($params['money_type']==2){
           if($user['giftamount']<floatval($params['puffs']*$pro['bond'])) return $this->echoJson(Lang::get('Amountfew')); //虛擬金額
        }
        //获取产品现价
        $price = $this->model->getprice($pro['procode']);
        if(empty($price['price'])){
            return $this->echojson(Lang::get('Ordererror'));
        }
        //获取手续费
        if(isset($pro['fee'])&&!empty($pro['fee'])){
            $sx_fee = $pro['fee']*$params['puffs'];
        }else{
            $sx_fee = (new CommonModel())->getBaseinfo('keyname="payment"','content')['content']['order'];
            $sx_fee = round((floatval($params['puffs']*$pro['bond'])*$sx_fee)/100);
        }
        $params=[
            'order_no'=>getNumID(6,'order',1),//年月日加8位计数,order文件计数名称，1代表类别，1订单
            'type'=>$params['money_type'],
            'aid'=>$user['aid'],
            'pid'=>$user['pid'],
            'price'=>$pro['price']*$params['puffs'],
            'bond'=>$pro['bond']*$params['puffs'],
            'puffs'=>$params['puffs'],
            'proid'=>$pro['id'],
            'proname'=>$pro['title'],
            'titles'=>$pro['titles'],
            'procode'=>$pro['procode'],
            'updown'=>$params['order_type'],
            'buyprice'=>$price['price'],
            'sx_fee'=>$sx_fee,
            'status'=>1,
            'createtime'=>date('Y-m-d H:i:s',time())
        ];
        (new CommonModel())->startTrans();
        try {
            //获取下单余额控制参数
            $control['settleconf']=isset($control['settleconf'])?$control['settleconf']:2;
            if($params['type']==1){
                $amount = $user['amount'];
                $money = ($user['amount']-$params['bond']-$sx_fee);
                switch ($control['settleconf']) {
                    case 1:
                        if($money<0){
                            return $this->echoJson(Lang::get('Amountfew'));
                        }
                        break;
                    case 2:
                        if($money<=0){
                            return $this->echoJson(Lang::get('Amountfew'));
                        }
                        break;
                    default:
                            return $this->echoJson($this->error);
                        break;
                }
                $info = (new CommonModel())->updateAccount('aid='.$user['aid'],['amount'=>$money]);
            }elseif($params['type']==2){
                $amount = $user['giftamount'];
                $money = ($user['giftamount']-$params['bond']-$sx_fee);
                switch ($control['settleconf']) {
                    case 1:
                        if($money<0){
                            return $this->echoJson(Lang::get('Amountfew'));
                        }
                        break;
                    case 2:
                        if($money<=0){
                            return $this->echoJson(Lang::get('Amountfew'));
                        }
                        break;
                    default:
                           return $this->echoJson($this->error);
                        break;

                }
                $info = (new CommonModel())->updateAccount('aid='.$user['aid'],['giftamount'=>$money]);
            }
            $id=$this->model->addorder($params);
            $key = config('zerocontrol.order');
            $params['id']=$id;
            unset($params['titles']);
            $this->model->execRedis('hset',[$key,$id,json_encode($params)]);
            if($id){
                $data=[
                    'orderid'=>$id,
                    'type'=>1,
                    'proid'=>$pro['id'],
                    'buyprice'=>$price['price'],
                    'price'=>$pro['price']*$params['puffs'],
                    'bond'=>$pro['bond']*$params['puffs'],
                    'amount'=>$amount,
                    'backamount'=>$money,
                    'money'=>0,
                    'puffs'=>$params['puffs'],
                    'createtime'=>date('Y-m-d H:i:s',time())
                ];
                $this->model->addorderlog($data);
            }
            (new CommonModel())->commit();
            return $this->echojson($this->success);
        } catch (Exception $e) {
            (new CommonModel())->rollback();
            return $this->echojson(Lang::get('Parerror'));
        }
    }
    /**
     * 订单结算
     * @param array $ordersettle 
     * @param array $where 
     */ 
    public function ordersettle(){
        $params = post();
        //判斷參數是否存在
        if(empty($params['orderid'])) return $this->echoJson(Lang::get('Ordererror'));
        //判斷支付密碼及驗證
        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        $user=(new CommonModel())->getAccount('aid='.$this->login['aid'],['aid','amount','giftamount','pid','paypwd']);
        //獲取運營參數
        $key = config('zerocontrol.order');
        $orders = $this->model->execRedis('hget',[$key,$params['orderid']]);
        if(!empty($orders)){
            $orders = json_decode($orders,true);
        }else{
            return $this->echoJson(Lang::get('Nodata'));
        }
        $params=[
            'money'=>$orders['money'],
            'sellprice'=>$orders['sellprice'],
            'profitrate'=>$orders['profitrate'],
            'ratio'=>$orders['ratio'],
            'status'=>2,
            'win'=>$orders['win'],
            'updatetime'=>date('Y-m-d H:i:s',time())
        ];
        (new CommonModel())->startTrans();
        try {
            $this->model->updateorder('id='.$orders['id'],$params);
            $this->model->execRedis('hdel',[$key,$orders['id']]);
            $this->model->execRedis('hdel',[$key.$this->login['aid'],$orders['id']]);
            $money = $orders['money']>0?$orders['money']:0;
            if($money>0){
                switch ($orders['type']) {
                    case 1:
                        $amount=$user['amount'];
                        (new CommonModel())->updateAccount('aid='.$user['aid'],['amount'=>($amount+$money)]);
                        break;
                    case 2:
                        $amount=$user['giftamount'];
                        (new CommonModel())->updateAccount('aid='.$user['aid'],['giftamount'=>($amount+$money)]);
                        break;
                    default:
                        return $this->echojson(Lang::get('Parerror'));
                        break;
                }
            }else{
                switch ($orders['type']) {
                    case 1:
                        $amount=$user['amount'];
                        break;
                    case 2:
                        $amount=$user['giftamount'];
                        break;
                    default:
                        return $this->echojson(Lang::get('Parerror'));
                        break;
                }
            }
            $data=[
                'orderid'=>$orders['id'],
                'type'=>2,
                'proid'=>$orders['proid'],
                'buyprice'=>$orders['buyprice'],
                'sellprice'=>$orders['sellprice'],
                'price'=>$orders['price'],
                'bond'=>$orders['bond'],
                'amount'=>$amount,
                'backamount'=>$amount+$money,
                'money'=>$money,
                'puffs'=>$orders['puffs'],
                'createtime'=>date('Y-m-d H:i:s',time())
            ];
            $info = $this->model->addorderlog($data);
            (new CommonModel())->commit();
            return $this->echojson($this->success);
        } catch (Exception $e) {
            (new CommonModel())->rollback();
            return $this->echojson(Lang::get('Parerror'));
        }
    }
}